<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      //生成器 = function
      //适用于异步编程
      // yield 代码分隔符
      function* gen() {
        console.log("hello");
        let partOne = yield "第一部分";
        console.log(partOne); //partOne接收第二次next的参数
        let partTwo = yield "第二部分";
        console.log(partTwo); //partTwo接收第三次next的参数
        let partThrre = yield "第三部分";
        console.log(partThrre); //partThrie接收第四次next的参数
      }
      //生成器生成迭代器对象，通过调用next去执行
      //next()中可以传递参数，作为上一个yield的返回结果
      // 第二次next(parmas)，params作为第一个yield结果
      // 第三次next(parmas),params作为第二个yield结果
      const result = gen();

      // demo1 1s输出111 2s后输出222 3s后输出333
      //阻止回调地狱
      function* thread() {
        yield one();
        yield two();
        yield three();
      }
      function one() {
        setTimeout(() => {
          console.log("111");
          threadIterator.next();
        }, 1000);
      }
      function two() {
        setTimeout(() => {
          console.log("222");
          threadIterator.next();
        }, 2000);
      }
      function three() {
        setTimeout(() => {
          console.log("333");
          threadIterator.next();
        }, 3000);
      }
      const threadIterator = thread();

      //demo2 模拟调用接口获取用户的数据
      function getUserId() {
        setTimeout(() => {
          let data = "0320";
          iterator.next(data);
        }, 1000);
      }
      function getUserName(id) {
        setTimeout(() => {
          let data = "HY";
          const result = { id, name: data };
          iterator.next(result);
        }, 1000);
      }
      function getUserInfo(name) {
        setTimeout(() => {
          let data = "hy-0320";
          iterator.next({ ...name, data });
        }, 1000);
      }
      function* userThread() {
        let id = yield getUserId();
        let name = yield getUserName(id);
        let userInfo = yield getUserInfo(name);
        console.log(userInfo); //输出{id:'0320',name:'HY',data:'hy-0320'}
      }
      const iterator = userThread();
      iterator.next();
    </script>
  </body>
</html>
